﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Xml.Linq;
using Runda.CMS.Common.Entity;
using System.Collections.Generic;
using Runda.CMS.Bll;
using Runda.CMS.Common.Utility;

namespace Runda.CMS.Portal.ContractFollowUp
{
    public partial class MaintainBasicApprove : BasePage
    {
        public Guid RegisterID
        {
            get
            {
                if (hiddenRegisterID.Value == string.Empty) return Guid.Empty;
                else return new Guid(hiddenRegisterID.Value);
            }
            set
            {
                hiddenRegisterID.Value = value.ToString();
            }
        }

        public Guid MaintainID
        {
            get
            {
                if (hiddenMaintainID.Value == string.Empty) return Guid.Empty;
                else return new Guid(hiddenMaintainID.Value);
            }
            set
            {
                hiddenMaintainID.Value = value.ToString();
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            lnkbtnSaveAndCloseTenal.Visible = false;
            lnkbtnSaveAndClose.Visible = false;
            if (!IsPostBack)
            {
                if (Request.QueryString["Type"] != null)
                {
                    hidPageType.Value = Request.QueryString["Type"];
                }
                if (Request.QueryString["RegisterID"] != null)
                {
                    GuaranteeInfo.BindEnum(EnumeratorHelper.GetFieldTexts(typeof(Enumerator.GuaranteeType)));
                    RegisterID = new Guid(Request.QueryString["RegisterID"]);
                    WsmTaskRegisterEntity registerEntity = new SystemBll().Get<WsmTaskRegisterEntity>(RegisterID);
                    List<WsmCustomerContactorEntity> contactors = new SystemBll().GetAll<WsmCustomerContactorEntity>(" and CustomerID = '" + registerEntity.CustomerID.ToString() + "'");
                    foreach (WsmCustomerContactorEntity contactor in contactors)
                    {
                        UsersContacter.Items.Add(new ListItem(contactor.ContactorName, contactor.ContactorID.ToString()));
                    }
                    if (registerEntity.TaskStatus == 1)
                    {
                        lnkbtnSaveAndClose.Visible = false;
                    }

                    if (registerEntity.TaskType == (int)Enumerator.SalesService.RepairFE || registerEntity.TaskType == (int)Enumerator.SalesService.RepairLS)
                    {
                        Panel1.Attributes.Add("style", "display:block");
                    }
                    else
                    {
                        Panel1.Attributes.Add("style", "display:none");
                    }

                    CtrtCustomerEntity cusEntity = new SystemBll().Get<CtrtCustomerEntity>(registerEntity.CustomerID);
                    customerName.Text = cusEntity.CustomerName;
                    linkContactor.OnClientClick = JsExtension.CreateModalWindowScript("../LookUp/CustomerContactorAdd.aspx?CustomerID=" + cusEntity.CustomerID.ToString(), "", 520, 300);
                    WsmCustomerExtensionEntity extensionEntity = new SystemBll().Get<WsmCustomerExtensionEntity>(registerEntity.CustomerID);
                    if (extensionEntity != null)
                    {
                        ServiceLevel.SelectedValue = extensionEntity.ServiceLevel;
                    }
                    hiddenWorkType.Value = System.Convert.ToInt32(registerEntity.TaskType).ToString();
                    WsmInstrumentInfoEntity InstrumentEntity = new SystemBll().Get<WsmInstrumentInfoEntity>(registerEntity.InstrumentID);
                    if (InstrumentEntity != null)
                    {
                        InstrumentName.Text = InstrumentEntity.instrumentName;
                        InstrumentBelongTo.Text = InstrumentEntity.Vendor;
                        InstrumentID.Text = InstrumentEntity.InstrumentID.ToString();
                    }
                    InstrumentSerialNum.Text = registerEntity.InstrumentSerialNum;
                    List<WsmMaintainBillEntity> list = new SystemBll().GetAll<WsmMaintainBillEntity>(" and RegisterID='" + Request.QueryString["RegisterID"] + "'");


                    DataTable bindenum = new MaintainBillBll().getComponentByInsurmentID(registerEntity.InstrumentID);

                    ddlFaultComponents.DataSource = bindenum;
                    ddlFaultComponents.DataValueField = "ComponentName";
                    ddlFaultComponents.DataTextField = "ComponentName";
                    ddlFaultComponents.DataBind();

                    if (list != null && list.Count > 0)
                    {
                        WsmMaintainBillEntity entity = list[0];
                        MaintainID = entity.MaintainID;
                        maintainBillNum.Text = entity.PaperInvoicesNo;
                        employeeGUID.Value = entity.Maintainer.ToString();
                        if (entity.Maintainer != Guid.Empty)
                        {
                            employeeName.Text = new SystemBll().Get<SysUserEntity>(entity.Maintainer).UserName;
                        }
                        else //默认为登陆用户
                        {
                            employeeGUID.Value = base.CurrentUserID.ToString();
                            employeeName.Text = base.CurrentUserEntity.UserName.ToString();
                        }
                        InstrumentSerialNum.Text = entity.InstrumentSerialNum;
                        GuaranteeInfo.SelectedValue = entity.GuaranteeInfo;

                        ServicePurpose.Text = entity.ServicePurpose;
                        ReceiveDate.SelectedDate = entity.ReceiveDate;
                        BeginDate.SelectedDate = entity.BeginDate;
                        OnWayTime.Value = System.Convert.ToDouble(entity.OnWayTime);
                        RecommendContent.Text = entity.RecommendContent;

                        txtReachFare.Value = Convert.ToDouble(entity.ReachFare);

                        txtLeaveFare.Value = Convert.ToDouble(entity.LeaveFare);

                        txtAccommodationFee.Value = Convert.ToDouble(entity.AccommodationFee);

                        txtEndTime.SelectedDate = entity.EndTime;

                        UsersContacter.SelectedValue = entity.UsersContacter;
                        txtWorkContent.Text = entity.WorkContent;
                        txtFaultCode.Text = entity.FaultCode;
                        ddlFaultComponents.SelectedValue = entity.FaultComponents;

                        if (entity.RelateMaintainBillID != Guid.Empty)
                        {
                            WsmMaintainBillEntity relateEntity = new SystemBll().Get<WsmMaintainBillEntity>(entity.RelateMaintainBillID);
                            txtPaperInvoicesNo.Text = relateEntity.PaperInvoicesNo;
                            IsLinkBill.Checked = true;
                        }
                        txtServicedStatus.Text = entity.ServicedStatus;
                    }
                    else
                    {
                        employeeGUID.Value = base.CurrentUserID.ToString();
                        employeeName.Text = base.CurrentUserEntity.UserName.ToString();
                    }
                }
            }
        }

        private bool isValidate(ref string message)
        {
            bool isValidate = true;
            if (employeeGUID.Value.Trim() == "")
            {
                message = "请输入现场执行人员";
            }
            if (ReceiveDate.SelectedDate == null)
            {
                message = "请输入获悉时间";
            }
            if (BeginDate.SelectedDate == null)
            {
                message = "请输入开始时间";
            }
            if (BeginDate.SelectedDate.Value.CompareTo(ReceiveDate.SelectedDate.Value) < 0)
            {
                message = "开始时间不能早于获悉时间";
            }
            if (OnWayTime.Value == null)
            {
                message = "请输入路途时间";
            }
            if (ServicePurpose.Text.Trim() == "")
            {
                message = "请输入服务目的";
            }
            if ((Enumerator.SalesService)Convert.ToInt32(hiddenWorkType.Value) == Enumerator.SalesService.RepairLS || (Enumerator.SalesService)Convert.ToInt32(hiddenWorkType.Value) == Enumerator.SalesService.RepairFE)
            {
                if (txtFaultCode.Text.Trim() == "")
                {
                    message = "请输入故障代码";
                }
                if (ddlFaultComponents.SelectedValue == null)
                {
                    message = "请输入故障组件";
                }
            }
            if (txtEndTime.SelectedDate == null)
            {
                message = "请输入结束时间";
            }
            if (txtEndTime.SelectedDate.Value.CompareTo(BeginDate.SelectedDate.Value) <= 0)
            {
                message = "结束时间不能早于开始时间";
            }
            if (txtServicedStatus.Text.Trim() == "")
            {
                message = "请输入 服务后仪器状态";
            }
            if (txtWorkContent.Text.Trim() == "")
            {
                message = "请输入 工作内容";
            }
            //if (RecommendContent.Text.Trim() == "")
            //{
            //    message = "请输入建议用户内容";
            //}

            if (IsLinkBill.Checked)
            {
                if (txtPaperInvoicesNo.Text.Trim() == "")
                {
                    message = "请输入纸质单据号";
                }
            }
            else
            {
                if (txtReachFare.Value == null)
                {
                    message = "请输入到达用户车费";
                }
                if (txtLeaveFare.Value == null)
                {
                    message = "请输入离开用户车费";
                }
                if (txtAccommodationFee.Value == null)
                {
                    message = "请输入住宿费用";
                }
            }
            if (message != "")
            {
                isValidate = false;
            }
            return isValidate;
        }

        protected void lnkbtnSaveAndClose_Click(object sender, EventArgs e)
        {
            string Message = "";
            if (!save(ref Message))
            {
                ClientScript.RegisterStartupScript(this.GetType(), "saveandssscloseerror", "alert('" + Message + "');", true);
                return;
            }
            else
            {
                ClientScript.RegisterStartupScript(this.GetType(), "saveandclose", "window.close();", true);
            }
        }

        protected void lnkbtnSaveAndCloseTenal_Click(object sender, EventArgs e)
        {
            string Message = "";
            if (!tenalSave(ref Message))
            {
                ClientScript.RegisterStartupScript(this.GetType(), "saveandssscloseerror", "alert('" + Message + "');", true);
                return;
            }
            else
            {
                ClientScript.RegisterStartupScript(this.GetType(), "saveandclose", "window.close();", true);
            }
        }

        protected void lnkbtnSaveAndNew_Click(object sender, EventArgs e)
        {
            string Message = "";
            if (!save(ref Message))
            {
                ClientScript.RegisterStartupScript(this.GetType(), "saveansrror", "alert('" + Message + "');", true);
            }
            else
            {
                RegisterID = Guid.Empty;
                MaintainID = Guid.Empty;
                InstrumentBelongTo.Text = "";
                InstrumentSerialNum.Text = "";
                ServiceLevel.Text = "";
                ServicePurpose.Text = "";
                ReceiveDate.SelectedDate = null;
                BeginDate.SelectedDate = null;
                OnWayTime.Value = null;
                RecommendContent.Text = "";
                maintainBillNum.Text = "";
                ClientScript.RegisterStartupScript(this.GetType(), "saveandnew", "alert('保存成功');", true);
            }
        }

        private bool tenalSave(ref string message)
        {
            if (RegisterID == Guid.Empty)
            {
                message = "传递参数有误";
                return false;
            }
            bool isSuccess = true;
            WsmMaintainBillEntity entity = new WsmMaintainBillEntity();
            SystemBll bll = new SystemBll();
            if (MaintainID != Guid.Empty)
            {
                entity = bll.Get<WsmMaintainBillEntity>(MaintainID);
            }
            else
            {
                entity = new WsmMaintainBillEntity();
                entity.PaperInvoicesNo = new CommonBll().getCode("PaperInvoicesNo");
                MaintainID = entity.MaintainID;
                entity.CreatedBy = CurrentUserID;
                entity.CreatedOn = DateTime.Now;
                entity.Deleted = 0;
                entity.RegisterID = RegisterID;
            }
            WsmTaskRegisterEntity taskEntity = bll.Get<WsmTaskRegisterEntity>(RegisterID);
            entity.GuaranteeInfo = GuaranteeInfo.SelectedValue;

            entity.ServiceLevel = ServiceLevel.SelectedValue;
            entity.ServicePurpose = ServicePurpose.Text.Trim();
            if (ReceiveDate.SelectedDate != null)
                entity.ReceiveDate = ReceiveDate.SelectedDate.Value;
            entity.RecommendContent = RecommendContent.Text.Trim();
            if (BeginDate.SelectedDate != null)
                entity.BeginDate = BeginDate.SelectedDate.Value;
            entity.OnWayTime = System.Convert.ToInt32(OnWayTime.Value);
            entity.InstrumentSerialNum = InstrumentSerialNum.Text.Trim();

            if (txtReachFare.Value.HasValue)
                entity.ReachFare = Convert.ToDecimal(txtReachFare.Value.Value);

            if (txtLeaveFare.Value.HasValue)
                entity.LeaveFare = Convert.ToDecimal(txtLeaveFare.Value.Value);

            if (txtAccommodationFee.Value.HasValue)
                entity.AccommodationFee = Convert.ToDecimal(txtAccommodationFee.Value.Value);
            if (txtEndTime.SelectedDate.HasValue)
                entity.EndTime = txtEndTime.SelectedDate.Value;

            entity.UsersContacter = UsersContacter.SelectedValue;
            entity.WorkContent = txtWorkContent.Text;
            entity.FaultCode = txtFaultCode.Text;
            entity.FaultComponents = ddlFaultComponents.SelectedValue.ToString();
            if (IsLinkBill.Checked)
            {
                if (txtPaperInvoicesNo.Text.Trim() != "")
                {
                    List<WsmMaintainBillEntity> relateEntitys = new SystemBll().GetAll<WsmMaintainBillEntity>(" and PaperInvoicesNo='" + txtPaperInvoicesNo.Text.Trim() + "'");
                    if (relateEntitys != null && relateEntitys.Count > 0)
                    {
                        entity.RelateMaintainBillID = relateEntitys[0].MaintainID;
                    }
                    else
                    {
                        message = "未找到关联单据号";
                        return false;
                    }
                }
                else
                {
                    message = "请输入关联单据号";
                    return false;
                }
            }
            else
            {
                entity.RelateMaintainBillID = Guid.Empty;
            }

            entity.ServicedStatus = txtServicedStatus.Text;
            entity.Maintainer = new Guid(employeeGUID.Value);
            bll.InsertOrUpdate(entity);
            return isSuccess;
        }

        private bool save(ref string message)
        {
            if (!isValidate(ref message))
            {
                return false;
            }
            if (RegisterID == Guid.Empty)
            {
                message = "传递参数有误";
                return false;
            }
            bool isSuccess = true;
            WsmMaintainBillEntity entity = new WsmMaintainBillEntity();
            SystemBll bll = new SystemBll();
            if (MaintainID != Guid.Empty)
            {
                entity = bll.Get<WsmMaintainBillEntity>(MaintainID);
            }
            else
            {
                entity = new WsmMaintainBillEntity();
                entity.PaperInvoicesNo = new CommonBll().getCode("PaperInvoicesNo");
                MaintainID = entity.MaintainID;
                entity.CreatedBy = CurrentUserID;
                entity.CreatedOn = DateTime.Now;
                entity.Deleted = 0;
                entity.RegisterID = RegisterID;
            }
            WsmTaskRegisterEntity taskEntity = bll.Get<WsmTaskRegisterEntity>(RegisterID);
            entity.GuaranteeInfo = GuaranteeInfo.SelectedValue;

            entity.ServiceLevel = ServiceLevel.SelectedValue;
            entity.ServicePurpose = ServicePurpose.Text.Trim();
            if (ReceiveDate.SelectedDate != null)
                entity.ReceiveDate = ReceiveDate.SelectedDate.Value;
            entity.RecommendContent = RecommendContent.Text.Trim();
            if (BeginDate.SelectedDate != null)
                entity.BeginDate = BeginDate.SelectedDate.Value;
            entity.OnWayTime = System.Convert.ToInt32(OnWayTime.Value);
            entity.InstrumentSerialNum = InstrumentSerialNum.Text.Trim();

            if (txtReachFare.Value.HasValue)
                entity.ReachFare = Convert.ToDecimal(txtReachFare.Value.Value);

            if (txtLeaveFare.Value.HasValue)
                entity.LeaveFare = Convert.ToDecimal(txtLeaveFare.Value.Value);

            if (txtAccommodationFee.Value.HasValue)
                entity.AccommodationFee = Convert.ToDecimal(txtAccommodationFee.Value.Value);
            if (txtEndTime.SelectedDate.HasValue)
                entity.EndTime = txtEndTime.SelectedDate.Value;

            entity.UsersContacter = UsersContacter.SelectedValue;
            entity.WorkContent = txtWorkContent.Text;
            entity.FaultCode = txtFaultCode.Text;
            entity.FaultComponents = ddlFaultComponents.SelectedValue.ToString();
            if (IsLinkBill.Checked)
            {
                if (txtPaperInvoicesNo.Text.Trim() != "")
                {
                    List<WsmMaintainBillEntity> relateEntitys = new SystemBll().GetAll<WsmMaintainBillEntity>(" and PaperInvoicesNo='" + txtPaperInvoicesNo.Text.Trim() + "'");
                    if (relateEntitys != null && relateEntitys.Count > 0)
                    {
                        entity.RelateMaintainBillID = relateEntitys[0].MaintainID;
                    }
                    else
                    {
                        message = "未找到关联单据号";
                        return false;
                    }
                }
                else
                {
                    message = "请输入关联单据号";
                    return false;
                }
            }
            else
            {
                entity.RelateMaintainBillID = Guid.Empty;
            }

            entity.ServicedStatus = txtServicedStatus.Text;
            entity.Maintainer = new Guid(employeeGUID.Value);
            bll.InsertOrUpdate(entity);
            taskEntity.TaskStatus = 1;
            bll.Update(taskEntity);
            return isSuccess;
        }

        protected void linkContactor_Click(object sender, EventArgs e)
        {
            UsersContacter.Items.Clear();
            WsmTaskRegisterEntity registerEntity = new SystemBll().Get<WsmTaskRegisterEntity>(RegisterID);
            List<WsmCustomerContactorEntity> contactors = new SystemBll().GetAll<WsmCustomerContactorEntity>(" and CustomerID = '" + registerEntity.CustomerID.ToString() + "'");
            foreach (WsmCustomerContactorEntity contactor in contactors)
            {
                UsersContacter.Items.Add(new ListItem(contactor.ContactorName, contactor.ContactorID.ToString()));
            }
        }

    }
}
